﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace xml
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //修改data.xml文件中的内容
            XmlDocument doc = new XmlDocument();
            doc.Load("data.xml");
            //获取根节点
            XmlNode rootNode = doc.SelectSingleNode("data");
            //获取根节点下面的total节点
            XmlNode totalNode = rootNode.SelectSingleNode("total");
            //读取total节点里面的文字内容
            string s = totalNode.InnerText;
            //转换成整型后+1
            int total = Convert.ToInt32(s) + 1;
            //将结果写回到total节点
            totalNode.InnerText = "" + total;
            //增加一个game节点到history节点下
            XmlNode historyNode = rootNode.SelectSingleNode("history");
            //创建一个game节点到history节点下
            XmlElement game = doc.CreateElement("game");
            Random rd = new Random();
            string time = "" + rd.Next(120);//设置时长
            game.SetAttribute("time", time);
            DateTime dtnow = System.DateTime.Now;
            game.SetAttribute("start", dtnow.ToString());
            //将game节点到history节点下
            historyNode.AppendChild(game);
            doc.Save("data.xml");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("data.xml");
            XmlNode rootNode = doc.SelectSingleNode("data");
            XmlNode totalNode = rootNode.SelectSingleNode("total");
            string total = totalNode.InnerText;
            MessageBox.Show("total的值为:" + total);
            //读取history里的内容
            listBox1.Items.Clear();
            XmlNode historyNode = rootNode.SelectSingleNode("history");
            //获取所有的子节点
            XmlNodeList list = historyNode.ChildNodes;
            foreach (XmlNode  node in list)
            {
                XmlElement element = (XmlElement)node;
                string time = element.GetAttribute("time");
                string start = element.GetAttribute("start");
                listBox1.Items.Add(time + "-------" + start);
            }
        }
    }
}
